package com.lp.service.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.iframework.commons.util.fast.V;
import org.iframework.support.spring.cache.api.BaseCacheConstants;
import org.iframework.support.spring.cache.api.BaseCacheManager;
import org.iframework.support.spring.interceptor.BaseSpringInterceptorSupport;

import com.alibaba.fastjson.JSON;
import com.lp.business.domain.Result;

/**
 * Token验证拦截器
 * @author lipeng
 * @date 2016年11月11日 下午4:37:25
 */
public class TokenValidatorInterceptor extends BaseSpringInterceptorSupport {
	@Resource(name = "baseCacheManager")
	private BaseCacheManager cacheManager;
	//不需要Token验证的链接
	private String[] noCheckUrl = {"/member/","/wxLogin","/industry"};

	/**
	 * token验证拦截器
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setCharacterEncoding("UTF-8");
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		if (StringUtils.length(pathInfo) > 0) {
		    servletPath = servletPath + pathInfo;
		}
		response.setContentType("application/json;charset=UTF-8");
		// 判断请求的URI是否运行放行，如果不允许则校验请求的token信息
		if (!this.isPassForCheckUrl(servletPath)) {
			//1.查看request是否有token值，没有，则校验失败
			String token = getTokenFromRequest(request);
			 if (StringUtils.isEmpty(token)) {
				 response.getWriter().write(JSON.toJSONString(Result.error("token为空")));
				 response.getWriter().close();
	             return false;
	        }
			//2.有，则查看token是否存在，不存在则校验失败
			 String memberId = (String) this.cacheManager.loadObject("token_"+token);
	        if (V.isEmpty(memberId)) {
	        	response.getWriter().write(JSON.toJSONString(Result.error("token验证失败")));
				response.getWriter().close();
	            return false;
	        }else{
		        cacheManager.cacheObject("token_"+token, memberId, BaseCacheConstants.CACHE_EXP_WEEK);
		        request.setAttribute("memberId", memberId);
	        }
		}
		return super.preHandle(request, response, handler);
	}
	
	/**
     * 从请求信息中获取token值
     * @param request
     * @return token值
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 默认从header里获取token值
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            // 从请求信息中获取token值
            token = request.getParameter("token");
        }
        return token;
    }
    
    /**
     * 是否直接跳过token校验
     * @param servletPath
     * @author lipeng
     * @date 2016年11月11日 下午4:32:37
     */
    private boolean isPassForCheckUrl(String servletPath) {
		boolean flag = false;
		for (int i = 0; i < noCheckUrl.length; i++) {
			if (servletPath.contains(noCheckUrl[i])) {
				flag = true;
				break;
			}
		}
		return flag;
	}
}
